package com.github.h4de5ing.kmp.rtk

import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.util.*

@Composable
fun AlertDialogExample(onConfirmation: () -> Unit = {}, onChange: (ByteArray) -> Unit) {
    val scope = rememberCoroutineScope()
    var isConfig by remember { mutableStateOf(false) }
    AlertDialog(title = { Text(text = "电台配置") }, onDismissRequest = { onConfirmation() }, confirmButton = {
        TButton(text = "关闭") { onConfirmation() }
    }, text = {
        Column {
            TButton(text = if (isConfig) "结束配置" else "开始配置") {
                if (isConfig) {
                    onChange(write("ATA"))
                } else {
                    onChange("+++".toByteArray())
                    scope.launch {
                        delay(2000)
                        onChange(write("AT&V"))
                    }
                }
                isConfig = !isConfig
            }
            TButton(text = "查询工作参数", enabled = isConfig) {
                onChange(write("AT&V"))
            }
            TButton(
                text = "测试发送",
                enabled = !isConfig
            ) { onChange("${os()}[${osArch()}] 测试通联 ${Date()}".toByteArray()) }
        }
    })
}

private fun write(message: String): ByteArray = (message.toByteArray() + byteArrayOf(0x0D, 0x0A))

private fun w(): ByteArray = "AT&W".toByteArray() + byteArrayOf(0x0D, 0x0A)

@Composable
fun TButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
    TextButton(onClick = onClick, enabled = enabled) {
        Text(text)
    }
}
